import { createMap, getQueryParam } from 'common'
import $ from 'jquery'

/**
 * @param {number} zoomLevel zoomLevel
 */
function calculateRadius(zoomLevel) {
  // 这里我们假设 zoomLevel 越高，圆的半径越小
  // 具体的计算公式可以根据你的需求调整
  return 1e3 / Math.pow(2, zoomLevel - 14.5)
}

/**
 * @param {[number, number]} center 位置中心
 * @param {number} radius 半径
 */
function getArea(center, radius) {
  return new Promise(function (resolve, reject) {
    $.ajax({
      url: '/api/map/near',
      method: 'post',
      data: $.param({ center, radius }),
      success(data) {
        resolve(data.data)
      },
      error: reject
    })
  })
}

function render(data, features) {
  resetMap.call(this, features)

  for (const item of data) {
    const marker = new AMap.Marker({
      position: new AMap.LngLat(item.lng, item.lat),
      title: item.title
    })

    marker.setLabel({
      direction: 'bottom',
      offset: new AMap.Pixel(0, 10),
      content: `<div style='padding: 1px 5px;'>${item.title}</div>`
    })

    features.push(marker)

    this.add(marker)
  }
}

async function bootstrap() {
  /**
   * @type {[string,string]|undefined}
   */
  const center = (function () {
    const result = getQueryParam('center')
    return result && result.split(',')
  })()

  const el = document.getElementById('map')
  const map = await createMap(el, { center })
  const radius = calculateRadius(map.getZoom())
  const features = []

  const circle = new AMap.Circle({
    center,
    radius
  })

  map.on('mapmove', async function () {
    const center = map.getCenter().toArray()
    const radius = calculateRadius(map.getZoom())
    circle.setCenter(center)

    const data = await getArea(center, radius / 1e3)
    render.apply(map, [data, features])
  })

  map.on('zoomchange', async function () {
    const radius = calculateRadius(map.getZoom())
    const center = map.getCenter().toArray()
    circle.setRadius(radius)

    const data = await getArea(center, radius / 1e3)
    render.apply(map, [data, features])
  })

  map.emit('mapmove')
  map.add(circle)
}

function resetMap(features) {
  for (const feature of features) {
    this.remove(feature)
  }
}

bootstrap()
